package com.qf.osmgrass.grass.service.Impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.GrassLike;
import com.qf.common.core.util.UserUtils;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.osmgrass.grass.mapper.GrassLikeMapper;
import com.qf.osmgrass.grass.service.GrassLikeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class GrassLikeServiceImpl implements GrassLikeService {

    @Resource
    private GrassLikeMapper grassLikeMapper;

    @Resource
    private RedisUtil  redisUtil;
    @Override
    public Integer like(Integer grassId) {
        Integer uid = UserUtils.getUid();
        String key = String.format("likeNum:%s", DateUtil.format(new Date(), "yyyyMMdd"));
        GrassLike grassLike = grassLikeMapper.selectOne(Wrappers.lambdaQuery(GrassLike.class)
                .eq(GrassLike::getGrassId , grassId)
                .eq(GrassLike::getUid , uid));
        if (grassLike == null){
            grassLike = new GrassLike();
            grassLike.setUid(uid);
            grassLike.setGrassId(grassId);
            grassLikeMapper.insert(grassLike);

            redisUtil.incrCacheMapValue(key, grassId.toString(), 1);
        }else {
            grassLikeMapper.deleteById(grassLike.getId());
            redisUtil.incrCacheMapValue(key, grassId.toString(), -1);
        }
        return uid;
    }

    @Override
    public List<GrassLike> listByGrassIdAndUid(List<Integer> ids, Integer uid) {
        return grassLikeMapper.selectList(Wrappers.lambdaQuery(GrassLike.class)
                .eq(GrassLike::getUid,uid)
                .eq(GrassLike::getGrassId,ids));

    }
}
